﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Events;

namespace YJKAxisAndEdit
{
	internal class AppRefreshAxisStatus : IExternalApplication
	{
		Result IExternalApplication.OnStartup(UIControlledApplication application)
		{
			this.AddAppDocEvents(application);
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		Result IExternalApplication.OnShutdown(UIControlledApplication application)
		{
			this.RemoveAppDocEvents(application);
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void AddAppDocEvents(UIControlledApplication app)
		{
			app.ViewActivated += this.viewActivated;
		}

		private void RemoveAppDocEvents(UIControlledApplication app)
		{
			app.ViewActivated -= this.viewActivated;
		}

		public void viewActivated(object sender, ViewActivatedEventArgs e)
		{
			View currentActiveView = e.CurrentActiveView;
			this.m_Doc = currentActiveView.Document;
			if (this.m_Doc == null)
			{
				return;
			}
			Dictionary<ElementId, List<GridStatusEachView>> dicGridStatus = null;
			List<ElementId> lstSelGridId = null;
			this.getGridBubblesXdata(out dicGridStatus, out lstSelGridId);
			HideOrShowGridTag.ModifyGridStatusByXdata(lstSelGridId, this.m_Doc, dicGridStatus);
		}

		private void getGridBubblesXdata(out Dictionary<ElementId, List<GridStatusEachView>> DicGridStatus, out List<ElementId> lstGridId)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_Doc);
			ElementClassFilter elementClassFilter = new ElementClassFilter(typeof(Grid));
			filteredElementCollector.WherePasses(elementClassFilter).WhereElementIsNotElementType();
			lstGridId = new List<ElementId>();
			DicGridStatus = new Dictionary<ElementId, List<GridStatusEachView>>();
			foreach (Element element in filteredElementCollector)
			{
				List<GridStatusEachView> value = new List<GridStatusEachView>();
				bool flag = GridXdataManger.ReadBubbleStatus(element, ref value);
				if (flag)
				{
					lstGridId.Add(element.Id);
					DicGridStatus.Add(element.Id, value);
				}
			}
		}

		private Document m_Doc;
	}
}
